<template>
	<view class="order">
		<u-list>
			<u-list-item v-for="(item, index) in orderList" :key="item.id">
				<view class="item">
					<view class="name">
						{{item.name}}
					</view>
					<view class="bsq">
						<view>变速箱：{{item.bianSuQi}}</view>
						<view>座位：{{item.seats}}</view>
					</view>
					<view class="bsq">
						<view>年代：{{item.year}}</view>
						<view>购买时间：{{item.create_time | fmTime}}</view>
					</view>
					<view class="btns">
						<view class="delete" @click="delOrder(item.id)">
							删除
						</view>
					</view>
				</view>
			</u-list-item>
		</u-list>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				orderList: []
			}
		},
		methods: {
			async loadOrder() {
				let mine = uni.getStorageSync("mine")
				if (!mine) {
					uni.showModal({
						content: '请登录后查看订单',
						success: ({
							confirm
						}) => {
							if (confirm) {
								uni.setStorageSync('navigateType', 'switchTab')
								uni.setStorageSync('url', '/pages/order/order')
								uni.switchTab({
									url: '/pages/mine/mine'
								})
							}
						}
					})
					return
				}
				mine = JSON.parse(mine)
				let {
					count,
					data
				} = await uni.$get('getAllOrder', {
					userId: mine.id,
					pageIndex: this.pageIndex,
					pageSize: 10
				})
				data.forEach(async r => {
					let car = await uni.$get('getCarById', {
						id: r.carId
					})
					r.bianSuQi = car.bianSuQi
					r.name = car.name
					r.seats = car.seats
					r.year = car.year
					this.$forceUpdate()
				})
				this.orderList = data

			},
			delOrder(id) {
				uni.showModal({
					content: '确定要删除吗？',
					success: async ({
						confirm
					}) => {
						if (confirm) {
							let ret = await uni.$post('delOrder', {
								id
							})
							if (ret) {
								uni.showToast({
									title: '删除成功'
								})
								// 刷新数据
								this.loadOrder()
							}
						}
					}
				})
			}
		},
		filters: {
			fmTime(val) {
				function repair0(val) {
					return (val + '').length > 1 ? val : '0' + val
				}
				let date = new Date(parseInt(val))
				let year = date.getFullYear()
				let month = date.getMonth() + 1
				let day = date.getDate()
				return [year, month, day].map(r => repair0(r)).join('-')
			}
		},
		onShow() {
			this.loadOrder()
		}
	}
</script>

<style scoped lang="scss">
	.order {
		padding: 0 10px;

		.item {
			padding: 10px 0;
			border-bottom: 1px solid #eee;

			.name {
				font-weight: bold;
				margin-bottom: 5px;
			}

			.bsq {
				display: flex;
				justify-content: space-between;
				margin: 5px 0;
			}

			.btns {
				display: flex;
				justify-content: flex-end;

				.delete {
					border: 1px solid tomato;
					width: 100px;
					height: 26px;
					line-height: 26px;
					text-align: center;
					color: tomato;
					border-radius: 4px;
				}
			}
		}
	}
</style>
